define(["module", "../Tile", "react", "../../../data/data"], function (module, Tile, React, StripeData) {
    "use strict";

    var InitPage = React.createClass({
        displayName: "InitPage",
        renderPolygons: function renderPolygons(map) {
            var format = new OpenLayers.Format.WKT({
                extractStyles: true,
                'internalProjection': map.baseLayer.projection,
                'externalProjection': new OpenLayers.Projection("EPSG:4326")
            });

            var features = StripeData.map(function (item) {
                var wkt = item.wkt;

                return format.read(wkt);
            });

            var vectorLayer = new OpenLayers.Layer.Vector("vectorLayer");
            vectorLayer.addFeatures(features);

            map.addLayer(vectorLayer);

            var imageLayer = new OpenLayers.Layer.ImageLayer("imgLayer");

            map.addLayer(imageLayer);

            this.renderImages(features, imageLayer, map);
        },
        renderImages: function renderImages(features, imageLayer, map) {
            features.forEach(function (feature, index) {
                var bounds = feature.geometry.bounds;

                var item = StripeData[index];

                var image = new OpenLayers.Layer.Image(item.name, { isBaseLayer: false,
                    alwaysInRange: true,
                    url: '../data/' + item.name + '/' + item.fileURL,
                    extent: bounds,
                    targetPolygon: feature.geometry,
                    size: new OpenLayers.Size(512, 512)
                });

                // var scope = this;
                // image.events.on({
                //     loadend: function() {
                //         var lt = map.getPixelFromLonLat(new OpenLayers.LonLat(bounds.left, bounds.top));
                //         var rb = map.getPixelFromLonLat(new OpenLayers.LonLat(bounds.right, bounds.bottom));
                //         var from = [[lt.x,lt.y],[lt.x,rb.y],[rb.x,lt.y],[rb.x,rb.y]];
                //         var coords = feature.geometry.components[0].components;
                //
                //         var to = [];
                //         var rt_p = scope.getMaxPoint(coords, "x");
                //         var lt_p = scope.getMaxPoint(coords, "y");
                //         var rb_p = scope.getMinPoint(coords, "y");
                //         var lb_p = scope.getMinPoint(coords, "x");
                //         var lt_px = map.getPixelFromLonLat(new OpenLayers.LonLat(lt_p.x, lt_p.y));
                //         var rt_px = map.getPixelFromLonLat(new OpenLayers.LonLat(rt_p.x, rt_p.y));
                //         var rb_px = map.getPixelFromLonLat(new OpenLayers.LonLat(rb_p.x, rb_p.y));
                //         var lb_px = map.getPixelFromLonLat(new OpenLayers.LonLat(lb_p.x, lb_p.y));
                //         to.push([lt_px.x, lt_px.y]);
                //         to.push([lb_px.x, lb_px.y]);
                //         to.push([rt_px.x, rt_px.y]);
                //         to.push([rb_px.x, rb_px.y]);
                //
                //         scope.applyTransform(image.tile.imgDiv, from, to);
                //     }
                // });

                imageLayer.addImage(image);
            }, this);
        },
        getTransform: function getTransform(from, to) {
            var A, H, b, h, i, k, k_i, l, lhs, m, ref, rhs;
            console.assert(from.length === (ref = to.length) && ref === 4);
            A = [];
            for (i = k = 0; k < 4; i = ++k) {
                A.push([from[i].x, from[i].y, 1, 0, 0, 0, -from[i].x * to[i].x, -from[i].y * to[i].x]);
                A.push([0, 0, 0, from[i].x, from[i].y, 1, -from[i].x * to[i].y, -from[i].y * to[i].y]);
            }
            b = [];
            for (i = l = 0; l < 4; i = ++l) {
                b.push(to[i].x);
                b.push(to[i].y);
            }
            h = numeric.solve(A, b);
            H = [[h[0], h[1], 0, h[2]], [h[3], h[4], 0, h[5]], [0, 0, 1, 0], [h[6], h[7], 0, 1]];
            for (i = m = 0; m < 4; i = ++m) {
                lhs = numeric.dot(H, [from[i].x, from[i].y, 0, 1]);
                k_i = lhs[3];
                rhs = numeric.dot(k_i, [to[i].x, to[i].y, 0, 1]);
                console.assert(numeric.norm2(numeric.sub(lhs, rhs)) < 1e-9, 'Not equal:', lhs, rhs);
            }
            return H;
        },
        applyTransform: function applyTransform(element, originalPos, targetPos) {
            var H, from, i, j, p, to;
            from = function () {
                var k, len, results;
                results = [];
                for (k = 0, len = originalPos.length; k < len; k++) {
                    p = originalPos[k];
                    results.push({
                        x: p[0] - originalPos[0][0],
                        y: p[1] - originalPos[0][1]
                    });
                }
                return results;
            }();
            to = function () {
                var k, len, results;
                results = [];
                for (k = 0, len = targetPos.length; k < len; k++) {
                    p = targetPos[k];
                    results.push({
                        x: p[0] - originalPos[0][0],
                        y: p[1] - originalPos[0][1]
                    });
                }
                return results;
            }();
            H = this.getTransform(from, to);

            var m11, m12, m21, m22;
            $(element).css({
                'transform': 'matrix3d(' + function () {
                    var k, results;
                    results = [];
                    for (i = k = 0; k < 4; i = ++k) {
                        results.push(function () {
                            var l, results1;
                            results1 = [];
                            for (j = l = 0; l < 4; j = ++l) {
                                results1.push(H[j][i].toFixed(20));
                            }
                            return results1;
                        }());
                    }
                    m11 = results[0][0];
                    m12 = results[1][0];
                    m21 = results[0][1];
                    m22 = results[1][1];
                    return results;
                }().join(',') + ')',
                'transform-origin': '0 0',
                'filter': "progid:DXImageTransform.Microsoft.Matrix(M11=" + m11 + ",M12=" + m12 + ",M21=" + m21 + ",M22=" + m22 + ",SizingMethod='auto expand')"
            });
        },
        getMaxPoint: function getMaxPoint(coords, xy) {
            var max = 0,
                point;
            coords.forEach(function (coord) {
                if (coord[xy] > max) {
                    max = coord[xy];
                    point = coord;
                }
            });

            return point;
        },
        getMinPoint: function getMinPoint(coords, xy) {
            var min = 10000000000,
                point;
            coords.forEach(function (coord) {
                if (coord[xy] < min) {
                    min = coord[xy];
                    point = coord;
                }
            });

            return point;
        },
        componentDidMount: function componentDidMount() {
            // var layers = this.renderPolygons();

            var map = new OpenLayers.Map({
                div: "map",
                layers: [new OpenLayers.Layer.OSM()],
                center: new OpenLayers.LonLat(116, 41).transform("EPSG:4326", "EPSG:900913"),
                zoom: 4
            });

            this.renderPolygons(map);
        },
        render: function render() {
            return React.createElement(
                "div",
                { className: "container" },
                React.createElement(
                    Tile,
                    { header: "ol2 旋转" },
                    React.createElement("div", { id: "map", style: { height: "600px" } })
                )
            );
        }
    });

    module.exports = InitPage;
});
